﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Kay.Nuget.Helper.WindowsApi;
using Newtonsoft.Json;

// 参考:https://docs.microsoft.com/zh-cn/nuget/tools/nuget-exe-cli-reference#add

namespace Kay.Nuget.Helper
{
    /// <summary>
    /// 启动窗体
    /// <para>程序主界面</para>
    /// </summary>
    public partial class Startup : Form
    {
        /// <summary>
        /// 当前文件名
        /// </summary>
        private string _currentFileName;

        /// <summary>
        /// 当前项目是否已经改变
        /// </summary>
        private bool _isChanged;

        /// <summary>
        /// 获取或设置当前项目
        /// </summary>
        public NugetProject Project { get; set; }

        /// <summary>
        /// 获取当前是否存在项目
        /// </summary>
        public bool HasProject => Project != null;

        /// <summary>
        /// 相对路径的基础目录
        /// </summary>
        public string _baseDirectory;

        /// <summary>
        /// 初始化逻辑操作
        /// </summary>
        public Startup()
        {
            InitializeComponent();
        }

        // 窗体加载事件
        private void Startup_Load(object sender, EventArgs e)
        {
            var afterVista = (Environment.OSVersion.Platform == PlatformID.Win32NT &&
                              Environment.OSVersion.Version.Major >= 6);
            if (afterVista)
            {
                var iconInfo = new Shstockiconinfo();
                iconInfo.cbSize = (uint)Marshal.SizeOf(iconInfo);
                Api.SHGetStockIconInfo(Shstockiconid.SiidShield, Shgsi.ShgsiIcon | Shgsi.ShgsiSmallicon, ref iconInfo);
                var icon = Icon.FromHandle(iconInfo.hIcon);
                toolStripMenuItem_Relevance_File.Image = icon.ToBitmap();
                toolStripMenuItem_Cancel_Relevance_File.Image = icon.ToBitmap();
            }
        }

        // 点击新建菜单
        private void toolStripMenuItem_New_Click(object sender, EventArgs e)
        {
            if (HasProject)
            {
                var result = MessageBox.Show(this, @"确认关闭当前项目？", @"提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    if (_isChanged)
                    {
                        result = MessageBox.Show(this, @"是否保存已修改内容？", @"提示", MessageBoxButtons.YesNoCancel,
                            MessageBoxIcon.Information);
                        if (result == DialogResult.Yes)
                        {
                            if (string.IsNullOrEmpty(_currentFileName) || _currentFileName.Trim() == string.Empty)
                            {
                                result = saveFileDialog.ShowDialog(this);
                                if (result == DialogResult.OK)
                                {
                                    _currentFileName = saveFileDialog.FileName;
                                }
                                else
                                {
                                    return;
                                }
                            }
                            var jsonProjectString = JsonConvert.SerializeObject(Project);
                            File.WriteAllText(_currentFileName, jsonProjectString);
                        }
                        else if (result == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    return;
                }
            }

            Project = new NugetProject();
            _currentFileName = null;
            saveFileDialog.FileName = null;
            textBox_Proj.Clear();
            textBox_Package.Clear();
            textBox_Spec.Clear();
            textBox_Key.Clear();
            textBox_Source.Clear();
            textBox_Cmd.Clear();
            textBox_Key.ReadOnly = false;
            Project.LockKey = false;
            button_Lock_Key.Text = @"锁定";
            textBox_Source.Text = CustomConsts.DefaultSource;
            textBox_Source.ReadOnly = true;
            Project.LockSource = true;
            button_Lock_Source.Text = @"解锁";
            Project.Url = textBox_Source.Text;
            Text = CustomConsts.TitleStartup + @" - *[New Project]";

            IsChanged();
        }

        // 点击打开菜单
        private void toolStripMenuItem_Open_Click(object sender, EventArgs e)
        {
            DialogResult result;
            if (HasProject)
            {
                result = MessageBox.Show(this, @"确认关闭当前项目？", @"提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    if (_isChanged)
                    {
                        result = MessageBox.Show(this, @"是否保存已修改内容？", @"提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
                        if (result == DialogResult.Yes)
                        {
                            if (string.IsNullOrEmpty(_currentFileName) || _currentFileName.Trim() == string.Empty)
                            {
                                result = saveFileDialog.ShowDialog(this);
                                if (result == DialogResult.OK)
                                {
                                    _currentFileName = saveFileDialog.FileName;
                                }
                                else
                                {
                                    return;
                                }
                            }
                            var jsonProjectString = JsonConvert.SerializeObject(Project);
                            File.WriteAllText(_currentFileName, jsonProjectString);
                        }
                        else if (result == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    return;
                }
            }

            Project = null;
            _currentFileName = null;
            _isChanged = false;
            saveFileDialog.FileName = null;
            textBox_Proj.Clear();
            textBox_Package.Clear();
            textBox_Spec.Clear();
            textBox_Key.Clear();
            textBox_Source.Clear();
            textBox_Cmd.Clear();
            textBox_Key.ReadOnly = false;
            button_Lock_Key.Text = @"锁定";
            textBox_Source.Text = CustomConsts.DefaultSource;
            textBox_Source.ReadOnly = true;
            button_Lock_Source.Text = @"解锁";

            openFileDialog.Filter = CustomConsts.FilterKayNuget;
            openFileDialog.FileName = null;
            openFileDialog.Title = CustomConsts.TitleKayNuget;
            result = openFileDialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                _currentFileName = openFileDialog.FileName;
                var jsonProjectString = File.ReadAllText(_currentFileName);
                Project = JsonConvert.DeserializeObject<NugetProject>(jsonProjectString);

                textBox_Proj.Text = Project.Proj;
                textBox_Package.Text = Project.Nupkg;
                textBox_Spec.Text = Project.Nuspec;
                textBox_Key.Text = Project.Key;
                textBox_Source.Text = Project.Url;
                textBox_Key.ReadOnly = Project.LockKey;
                button_Lock_Key.Text = Project.LockKey ? @"解锁" : @"锁定";
                textBox_Source.ReadOnly = Project.LockSource;
                button_Lock_Source.Text = Project.LockSource ? @"解锁" : @"锁定";
                checkBox_IsRelativePath.Checked = Project.IsRelativePath;

                Text = CustomConsts.TitleStartup + @" - [" + _currentFileName + @"]";
            }
        }

        // 点击保存菜单
        private void toolStripMenuItem_Save_Click(object sender, EventArgs e)
        {
            if (HasProject)
            {
                if (_isChanged)
                {
                    if (string.IsNullOrEmpty(_currentFileName) || _currentFileName.Trim() == string.Empty)
                    {
                        var result = saveFileDialog.ShowDialog(this);
                        if (result == DialogResult.OK)
                        {
                            _currentFileName = saveFileDialog.FileName;

                            if (Project.IsRelativePath && string.IsNullOrWhiteSpace(_baseDirectory))
                            {
                                if (!string.IsNullOrWhiteSpace(_currentFileName))
                                {
                                    _baseDirectory = $"{Path.GetDirectoryName(_currentFileName)}{Path.DirectorySeparatorChar}";
                                }

                                if (!string.IsNullOrWhiteSpace(_baseDirectory))
                                {
                                    toolTip.SetToolTip(checkBox_IsRelativePath, _baseDirectory);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(this, @"你取消了保存！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
                    var jsonProjectString = JsonConvert.SerializeObject(Project);
                    File.WriteAllText(_currentFileName, jsonProjectString);
                    _isChanged = false;
                    Text = CustomConsts.TitleStartup + @" - [" + _currentFileName + @"]";
                }
            }
        }

        // 点击关闭菜单
        private void toolStripMenuItem_Close_Click(object sender, EventArgs e)
        {
            if (HasProject)
            {
                var result = MessageBox.Show(this, @"确认关闭当前项目？", @"提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    if (_isChanged)
                    {
                        result = MessageBox.Show(this, @"是否保存已修改内容？", @"提示", MessageBoxButtons.YesNoCancel,
                            MessageBoxIcon.Information);
                        if (result == DialogResult.Yes)
                        {
                            if (string.IsNullOrEmpty(_currentFileName) || _currentFileName.Trim() == string.Empty)
                            {
                                result = saveFileDialog.ShowDialog(this);
                                if (result == DialogResult.OK)
                                {
                                    _currentFileName = saveFileDialog.FileName;
                                }
                                else
                                {
                                    return;
                                }
                            }
                            var jsonProjectString = JsonConvert.SerializeObject(Project);
                            File.WriteAllText(_currentFileName, jsonProjectString);
                        }
                        else if (result == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    return;
                }
            }

            Project = null;
            _currentFileName = null;
            _isChanged = false;
            saveFileDialog.FileName = null;
            textBox_Proj.Clear();
            textBox_Package.Clear();
            textBox_Spec.Clear();
            textBox_Key.Clear();
            textBox_Source.Clear();
            textBox_Cmd.Clear();
            textBox_Key.ReadOnly = false;
            button_Lock_Key.Text = @"锁定";
            textBox_Source.Text = CustomConsts.DefaultSource;
            textBox_Source.ReadOnly = true;
            button_Lock_Source.Text = @"解锁";
            Text = CustomConsts.TitleStartup;
        }

        // 点击退出菜单
        private void toolStripMenuItem_Exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        // 执行 Pack {0} -Build -Symbols
        private void toolStripMenuItem_Build_Symbols_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Proj.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"没有项目文件！请选择！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var path = Path.GetDirectoryName(textBox_Proj.Text);
            var cmd = $@"Pack ""{Path.GetFileName(textBox_Proj.Text)}"" -Build -Symbols";
            ExecuteNuGetCommond(cmd, path);
        }

        // 执行 Pack {0}
        private void toolStripMenuItem_Pack1_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Proj.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"没有项目文件！请选择！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var path = Path.GetDirectoryName(textBox_Proj.Text);
            var cmd = $@"Pack ""{Path.GetFileName(textBox_Proj.Text)}""";
            ExecuteNuGetCommond(cmd, path);
        }

        // 执行 Pack {0} -Build
        private void toolStripMenuItem_Build_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Proj.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"没有项目文件！请选择！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var path = Path.GetDirectoryName(textBox_Proj.Text);
            var cmd = $@"Pack ""{Path.GetFileName(textBox_Proj.Text)}"" -Build";
            ExecuteNuGetCommond(cmd, path);
        }

        // 执行 Pack {0} -Symbols
        private void toolStripMenuItem_Symbols_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Proj.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"没有项目文件！请选择！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var path = Path.GetDirectoryName(textBox_Proj.Text);
            var cmd = $@"Pack ""{Path.GetFileName(textBox_Proj.Text)}"" -Symbols";
            ExecuteNuGetCommond(cmd, path);
        }

        // 执行 Pack -Help
        private void toolStripMenuItem_Help_Pack_Click(object sender, EventArgs e)
        {
            var cmd = "Pack -Help";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Push {0} -Key {1} -Source {2}
        private void toolStripMenuItem_Key_Source_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Proj.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"没有项目文件！请选择！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Package.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"没有包文件！请选择！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Key.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"请先设置 ApiKey！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Source.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"请先设置包源！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var package = textBox_Package.Text;
            if (Project.IsRelativePath)
            {
                package = Path.GetFullPath(Path.Combine(_baseDirectory, package));
            }

            var path = Path.GetDirectoryName(package);
            var cmd = $@"Push ""{Path.GetFileName(textBox_Package.Text)}"" {textBox_Key.Text} -Source {textBox_Source.Text}";
            ExecuteNuGetCommond(cmd, path);
        }

        // 执行 Push -Help
        private void toolStripMenuItem_Help_Push_Click(object sender, EventArgs e)
        {
            var cmd = "Push -Help";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Spec {0} -Force
        private void toolStripMenuItem_Force_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Proj.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"没有项目文件！请选择！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var path = Path.GetDirectoryName(textBox_Proj.Text);
            var cmd = $@"Spec ""{Path.GetFileName(textBox_Proj.Text)}"" -Force";
            ExecuteNuGetCommond(cmd, path);
        }

        // 执行 Spec {0}
        private void toolStripMenuItem_Spec1_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox_Proj.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"没有项目文件！请选择！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var path = Path.GetDirectoryName(textBox_Proj.Text);
            var cmd = $@"Spec ""{Path.GetFileName(textBox_Proj.Text)}""";
            ExecuteNuGetCommond(cmd, path);
        }

        // 执行 Spec -Help
        private void toolStripMenuItem_Help_Spec_Click(object sender, EventArgs e)
        {
            var cmd = "Spec -Help";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 SetApiKey {0}
        private void toolStripMenuItem_SetApiKey1_Click(object sender, EventArgs e)
        {
            if (textBox_Key.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"请填写 Apikey！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var cmd = new StringBuilder($"SetApiKey {textBox_Key.Text}");
            if (textBox_Source.Text.Trim() != string.Empty)
            {
                cmd.AppendFormat(" -Source {0}", textBox_Source.Text.Trim());
            }
            ExecuteNuGetCommond(cmd.ToString(), null);
        }

        // 执行 SetApiKey -Help
        private void toolStripMenuItem_Help_SetApiKey_Click(object sender, EventArgs e)
        {
            var cmd = "SetApiKey -Help";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Update -Self
        private void toolStripMenuItem_Self_Click(object sender, EventArgs e)
        {
            var cmd = "Update -Self";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Update -Help
        private void toolStripMenuItem_Help_Update_Click(object sender, EventArgs e)
        {
            var cmd = "Update -Help";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Help
        private void toolStripMenuItem_Help_NuGet_Click(object sender, EventArgs e)
        {
            var cmd = "Help";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Help Pack
        private void toolStripMenuItem_Pack_Help_Click(object sender, EventArgs e)
        {
            var cmd = "Help Pack";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Help Push
        private void toolStripMenuItem_Push_Help_Click(object sender, EventArgs e)
        {
            var cmd = "Help Push";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Help Spec
        private void toolStripMenuItem_Spec_Help_Click(object sender, EventArgs e)
        {
            var cmd = "Help Spec";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Help SetApiKey
        private void toolStripMenuItem_SetApiKey_Help_Click(object sender, EventArgs e)
        {
            var cmd = "Help SetApiKey";
            ExecuteNuGetCommond(cmd, null);
        }

        // 执行 Help Update
        private void toolStripMenuItem_Update_Help_Click(object sender, EventArgs e)
        {
            var cmd = "Help Update";
            ExecuteNuGetCommond(cmd, null);
        }

        // 打开 Spec 编辑器
        private void toolStripMenuItem_SpecEditor_Click(object sender, EventArgs e)
        {
            if (textBox_Spec.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, @"请填选择说明文件！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var spec = textBox_Spec.Text;
            if (Project.IsRelativePath)
            {
                spec = Path.GetFullPath(Path.Combine(_baseDirectory, spec));
            }

            var dlg = new SpecEditor(spec).ShowDialog();
            if (dlg == DialogResult.OK)
            {
                MessageBox.Show(@"修改成功！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                MessageBox.Show(@"取消修改！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        // 设置命令框自动换行
        private void toolStripMenuItem_WordWrap_Click(object sender, EventArgs e)
        {
            toolStripMenuItem_WordWrap.Checked = !toolStripMenuItem_WordWrap.Checked;
            textBox_Cmd.WordWrap = toolStripMenuItem_WordWrap.Checked;
        }

        // 清空命令框
        private void toolStripMenuItem_Clear_Click(object sender, EventArgs e)
        {
            textBox_Cmd.Clear();
        }

        // 设置程序与项目文件关联
        private void toolStripMenuItem_Relevance_File_Click(object sender, EventArgs e)
        {
            //var identity = WindowsIdentity.GetCurrent();
            //var principal = new WindowsPrincipal(identity);
            //var isRunasAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        // 取消程序与项目文件关联
        private void toolStripMenuItem_Cancel_Relevance_File_Click(object sender, EventArgs e)
        {

        }

        // 执行 Pack {0} -Build -Symbols
        private void toolStripButton_Build_Symbols_Click(object sender, EventArgs e)
        {
            toolStripMenuItem_Build_Symbols.PerformClick();
        }

        // 执行 Push {0} -Key {1} -Source {2}
        private void toolStripButton_Key_Source_Click(object sender, EventArgs e)
        {
            toolStripMenuItem_Key_Source.PerformClick();
        }

        // 执行 Spec {0} -Force
        private void toolStripButton_Force_Click(object sender, EventArgs e)
        {
            toolStripMenuItem_Force.PerformClick();
        }

        // 执行 SetApiKey {0}
        private void toolStripButton_SetApiKey_Click(object sender, EventArgs e)
        {
            toolStripMenuItem_SetApiKey1.PerformClick();
        }

        // 执行 Update -Self
        private void toolStripButton_Update_Click(object sender, EventArgs e)
        {
            toolStripMenuItem_Self.PerformClick();
        }

        // 打开 Spec 编辑器
        private void toolStripButton_SpecEditor_Click(object sender, EventArgs e)
        {
            toolStripMenuItem_SpecEditor.PerformClick();
        }

        // 打开项目文件
        private void button_Browse_Proj_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            openFileDialog.Filter = CustomConsts.FilterProj;
            openFileDialog.FileName = null;
            openFileDialog.Title = CustomConsts.TitleProj;
            if (!string.IsNullOrWhiteSpace(_currentFileName))
            {
                openFileDialog.InitialDirectory = Path.GetDirectoryName(_currentFileName);
            }
            var result = openFileDialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                if (Project.IsRelativePath && string.IsNullOrWhiteSpace(_baseDirectory))
                {
                    if (!string.IsNullOrWhiteSpace(_currentFileName))
                    {
                        _baseDirectory = $"{Path.GetDirectoryName(_currentFileName)}{Path.DirectorySeparatorChar}";
                    }
                    else if (!string.IsNullOrWhiteSpace(openFileDialog.FileName))
                    {
                        _baseDirectory = $"{Path.GetDirectoryName(openFileDialog.FileName)}{Path.DirectorySeparatorChar}";
                    }

                    if (!string.IsNullOrWhiteSpace(_baseDirectory))
                    {
                        toolTip.SetToolTip(checkBox_IsRelativePath, _baseDirectory);
                    }
                }

                if (Project.IsRelativePath)
                {
                    var baseUri = new Uri(_baseDirectory);
                    var uriPath = new Uri(openFileDialog.FileName);
                    var path = baseUri.MakeRelativeUri(uriPath);
                    textBox_Proj.Text = path.OriginalString.Replace('/', Path.DirectorySeparatorChar);
                    Project.Proj = path.ToString();
                }
                else
                {
                    textBox_Proj.Text = openFileDialog.FileName;
                    Project.Proj = openFileDialog.FileName;
                }

                IsChanged();
            }
        }

        // 打开包文件
        private void button_Browse_Package_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            openFileDialog.Filter = CustomConsts.FilterNupkg;
            openFileDialog.FileName = null;
            openFileDialog.Title = CustomConsts.TitleNupkg;
            if (!string.IsNullOrWhiteSpace(_currentFileName))
            {
                openFileDialog.InitialDirectory = Path.GetDirectoryName(_currentFileName);
            }
            var result = openFileDialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                if (Project.IsRelativePath)
                {
                    var baseUri = new Uri(_baseDirectory);
                    var uriPath = new Uri(openFileDialog.FileName);
                    var path = baseUri.MakeRelativeUri(uriPath);
                    textBox_Package.Text = path.OriginalString.Replace('/', Path.DirectorySeparatorChar);
                    Project.Nupkg = path.ToString();
                }
                else
                {
                    textBox_Package.Text = openFileDialog.FileName;
                    Project.Nupkg = openFileDialog.FileName;
                }
            }
        }

        // 打开说明书
        private void button_Browse_Spec_Click(object sender, EventArgs e)
        {
            if (!HasProject)
            {
                MessageBox.Show(this, @"项目不存在！请新建项目！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            openFileDialog.Filter = CustomConsts.FilterSpec;
            openFileDialog.FileName = null;
            openFileDialog.Title = CustomConsts.TitleSpec;
            if (!string.IsNullOrWhiteSpace(_currentFileName))
            {
                openFileDialog.InitialDirectory = Path.GetDirectoryName(_currentFileName);
            }
            var result = openFileDialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                if (Project.IsRelativePath)
                {
                    var baseUri = new Uri(_baseDirectory);
                    var uriPath = new Uri(openFileDialog.FileName);
                    var path = baseUri.MakeRelativeUri(uriPath);
                    textBox_Spec.Text = path.OriginalString.Replace('/', Path.DirectorySeparatorChar);
                    Project.Nuspec = path.ToString();
                }
                else
                {
                    textBox_Spec.Text = openFileDialog.FileName;
                    Project.Nuspec = openFileDialog.FileName;
                }

                IsChanged();
            }
        }

        // 锁定密钥
        private void button_Lock_Key_Click(object sender, EventArgs e)
        {
            if (button_Lock_Key.Text == @"锁定")
            {
                textBox_Key.ReadOnly = true;
                Project.LockKey = true;
                button_Lock_Key.Text = @"解锁";
            }
            else if (button_Lock_Key.Text == @"解锁")
            {
                textBox_Key.ReadOnly = false;
                Project.LockKey = false;
                button_Lock_Key.Text = @"锁定";
            }

            IsChanged();
        }

        // 锁定源
        private void button_Lock_Source_Click(object sender, EventArgs e)
        {
            if (button_Lock_Source.Text == @"锁定")
            {
                textBox_Source.ReadOnly = true;
                Project.LockSource = true;
                button_Lock_Source.Text = @"解锁";
            }
            else if (button_Lock_Source.Text == @"解锁")
            {
                textBox_Source.ReadOnly = false;
                Project.LockSource = false;
                button_Lock_Source.Text = @"锁定";
            }

            IsChanged();
        }

        // 窗体即将关闭
        private void Startup_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (HasProject)
            {
                toolStripMenuItem_Close.PerformClick();

                if (HasProject)
                {
                    e.Cancel = true;
                }
            }

        }

        /// <summary>
        /// 执行 NuGet 命令
        /// </summary>
        /// <param name="value">命令参数</param>
        /// <param name="dir">命令执行路径</param>
        public void ExecuteNuGetCommond(string value, string dir)
        {
            textBox_Cmd.Clear();
            toolStripStatusLabel1.Text = @"准备执行……";
            Application.DoEvents();
            var processStartInfo = new ProcessStartInfo()
            {
                FileName = "NuGet",
                Arguments = value,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                UseShellExecute = false
            };

            if (!string.IsNullOrEmpty(dir) && dir.Trim() != string.Empty)
            {
                processStartInfo.WorkingDirectory = dir;
            }

            textBox_Cmd.AppendText("> " + processStartInfo.FileName + " " + processStartInfo.Arguments);
            textBox_Cmd.AppendText(Environment.NewLine + ">");
            textBox_Cmd.Refresh();

            var process = new Process
            {
                StartInfo = processStartInfo,
                EnableRaisingEvents = true
            };

            process.OutputDataReceived += OnProcessOutputDataReceived;
            process.ErrorDataReceived += OnProcessErrorDataReceived;
            process.Exited += OnProcessExited;
            toolStripStatusLabel1.Text = @"正在执行……";
            Application.DoEvents();
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
        }

        private void OnProcessExited(object sender, EventArgs e)
        {
            if (textBox_Cmd.InvokeRequired)
            {
                textBox_Cmd.Invoke(new Action<object, EventArgs>(OnProcessExited), sender, e);
            }
            else
            {
                var p = (Process)sender;
                toolStripStatusLabel1.Text = @"执行完毕！";
                Application.DoEvents();
                var path = p.StartInfo.WorkingDirectory;
                if (!string.IsNullOrEmpty(path) && path.Trim() != string.Empty)
                {
                    var dirInfo = new DirectoryInfo(path);
                    var proj = Path.GetFileNameWithoutExtension(textBox_Proj.Text);
                    var projFile = textBox_Proj.Text;
                    if (Project.IsRelativePath)
                    {
                        projFile = Path.GetFullPath(Path.Combine(_baseDirectory, projFile));
                    }

                    if (projFile != null && File.Exists(projFile))
                    {
                        var xmlDocument = new XmlDocument();
                        xmlDocument.Load(projFile ?? string.Empty);
                        var node = xmlDocument.DocumentElement?["PropertyGroup"];
                        var element = node?["AssemblyName"];
                        if (element != null)
                        {
                            proj = element.InnerText;
                        }
                    }

                    var valueInfo = p.StartInfo.Arguments.Substring(0, 12);
                    if (valueInfo.IndexOf("Pack", StringComparison.Ordinal) != -1)
                    {
                        var fileInfos = dirInfo.GetFiles(proj + ".*.*.*.*.nupkg", SearchOption.TopDirectoryOnly);
                        if (fileInfos.Length > 0)
                        {
                            var query = fileInfos.Where(f => f.Name.IndexOf("symbols", StringComparison.Ordinal) == -1);
                            var list = query.OrderByDescending(f => f.CreationTime).ToList();
                            if (list.Count > 0)
                            {
                                textBox_Package.Text = list[0].FullName;
                            }
                        }
                    }
                    else if (valueInfo.IndexOf("Spec", StringComparison.Ordinal) != -1)
                    {
                        var fileInfos = dirInfo.GetFiles(proj + ".nuspec", SearchOption.TopDirectoryOnly);
                        if (fileInfos.Length > 0)
                        {
                            var list = fileInfos.OrderByDescending(f => f.CreationTime).ToList();
                            textBox_Spec.Text = list[0].FullName;
                        }
                    }
                }

                p.Close();
            }
        }

        private void OnProcessErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (textBox_Cmd.InvokeRequired)
            {
                textBox_Cmd.Invoke(new Action<object, DataReceivedEventArgs>(OnProcessErrorDataReceived), sender, e);
            }
            else
            {
                if (e.Data != null)
                {
                    if (textBox_Cmd.TextLength > 0)
                    {
                        textBox_Cmd.AppendText(Environment.NewLine);
                    }
                    textBox_Cmd.AppendText("> " + e.Data);
                }
            }
        }

        private void OnProcessOutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (textBox_Cmd.InvokeRequired)
            {
                textBox_Cmd.Invoke(new Action<object, DataReceivedEventArgs>(OnProcessOutputDataReceived), sender, e);
            }
            else
            {
                if (e.Data != null)
                {
                    if (textBox_Cmd.TextLength > 0)
                    {
                        textBox_Cmd.AppendText(Environment.NewLine);
                    }
                    textBox_Cmd.AppendText("> " + e.Data);
                }
            }
        }

        private void textBox_Proj_TextChanged(object sender, EventArgs e)
        {
            if (HasProject)
            {
                Project.Proj = textBox_Proj.Text;

                IsChanged();
            }
        }

        private void textBox_Package_TextChanged(object sender, EventArgs e)
        {
            if (HasProject)
            {
                Project.Nupkg = textBox_Package.Text;

                IsChanged();
            }
        }

        private void textBox_Spec_TextChanged(object sender, EventArgs e)
        {
            if (HasProject)
            {
                Project.Nuspec = textBox_Spec.Text;

                IsChanged();
            }
        }

        private void textBox_Key_TextChanged(object sender, EventArgs e)
        {
            if (HasProject)
            {
                Project.Key = textBox_Key.Text;

                IsChanged();
            }
        }

        private void textBox_Source_TextChanged(object sender, EventArgs e)
        {
            if (HasProject)
            {
                Project.Url = textBox_Source.Text;

                IsChanged();
            }
        }

        public void IsChanged()
        {
            _isChanged = true;
            if (!string.IsNullOrEmpty(_currentFileName) && _currentFileName.Trim() != string.Empty)
            {
                Text = CustomConsts.TitleStartup + @" - *[" + _currentFileName + @"]";
            }
        }

        /// <summary>
        /// 相对路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_IsRelativePath_CheckedChanged(object sender, EventArgs e)
        {
            if (HasProject)
            {
                Project.IsRelativePath = checkBox_IsRelativePath.Checked;

                if (Project.IsRelativePath)
                {
                    if (!string.IsNullOrWhiteSpace(_currentFileName))
                    {
                        _baseDirectory = $"{Path.GetDirectoryName(_currentFileName)}{Path.DirectorySeparatorChar}";
                    }
                    else if (!string.IsNullOrWhiteSpace(Project.Proj))
                    {
                        _baseDirectory = $"{Path.GetDirectoryName(Project.Proj)}{Path.DirectorySeparatorChar}";
                    }

                    if (!string.IsNullOrWhiteSpace(_baseDirectory))
                    {
                        toolTip.SetToolTip(checkBox_IsRelativePath, _baseDirectory);
                    }
                }
                else
                {
                    _baseDirectory = null;

                    toolTip.SetToolTip(checkBox_IsRelativePath, null);
                }

                IsChanged();
            }
        }
    }
}
